import { GridView, OType } from '@cscec/udp-ui';
import React, { useMemo } from 'react';
import { setTableColumnFormat } from '../util';

function getEditor(item: any, render: any, index: number) {
  if (item.xtype) {
    return { ...item };
  }
  return false;
}

export default ({
  columns, id, render, name, data, tableProps,
}: any) => {
  const innerColumns = useMemo(() => columns.map(({
    label, name, type, ...col
  }: any, index: number) => {
    const c = {
      langKey: name,
      ...col,
      title: label,
      dataIndex: name,
      editor: getEditor(col, render, index),
    };
    setTableColumnFormat(c);
    return c;
  }), [columns]);
  
  const cid = tableProps?.id || id || 'grid';
  const _showRowNumber = tableProps?.showRowNumber;
  const { oType = OType.Add, stateData = {} } = data || {};

  const disabled = ![OType.Add, OType.Edit].includes(oType);

  const showRowNumber = useMemo(() => {
    if (_showRowNumber?.editOptions) {
      return disabled ? true : _showRowNumber;
    }
    return _showRowNumber;
  }, [disabled, _showRowNumber]);

  const props = _showRowNumber?.editOptions ? {
    disabled,
    bordered: !disabled,
    showRowNumber,
  } : { showRowNumber };

  return <GridView cache={false} {...tableProps} {...props} id={cid} dataSource={stateData[name]} columns={innerColumns} />;
};
